﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Web.Security;
using Newtonsoft.Json.Linq;
using KL.Store.Data;
using KL.Store.Core.Domain;
using KL.Store.Web.Models;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using KL.Store.Core;

namespace KL.Store.Web.Controllers
{
    public class OAuthController : KL.Store.Core.Web.BaseController
    {
        #region FacebookLogin

        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            try
            {
                WebClient client = new WebClient();

                #region Get user details

                string jsonUserInfoResult = client.DownloadString(string.Concat("https://graph.facebook.com/me?access_token=", token));
                JObject jsonUserInfo = JObject.Parse(jsonUserInfoResult);

                //string faceUsername = jsonUserInfo.Value<string>("username");
                string faceID = jsonUserInfo.Value<string>("id");
                string email = jsonUserInfo.Value<string>("email");
                string name = jsonUserInfo.Value<string>("name");
                string firstName = jsonUserInfo.Value<string>("first_name");
                string lastName = jsonUserInfo.Value<string>("last_name");
                int VisitorId = eStoreUser.AccountId;

                if (string.IsNullOrEmpty(email))
                {
                    if (!string.IsNullOrEmpty(faceID))
                    {
                        email = faceID + "@facebook.com";
                    }
                    else
                    {
                        Session["###eStoreError"] = "Facebook ile bağlan işlemi için yeterli bilgi alınamadı!";
                        return RedirectToAction("Index", "Error");
                    }
                }

                #endregion

                Account account = dbAccount.Get(email);
                if (account == null)
                {
                    #region New account operation
                    int id = (int)dbAccount.Insert(
                                                    firstName ?? "",
                                                    lastName ?? "",
                                                    email,
                                                    new DateTime(1900, 1, 1),
                                                    string.Empty, //Address1,
                                                    string.Empty, //Address2,
                                                    string.Empty, //Address3,
                                                    string.Empty, //Address4,
                                                    0,            //City,
                                                    string.Empty, //Phone,
                                                    string.Empty, //Mobile,
                                                    string.Empty, //Fax,
                                                    string.Empty, //PhoneInternational,
                                                    string.Empty, //Password,
                                                    1,            //NewsLetter == true ? 1 : 0
                                                    1,            //campaignsms == true ? 1 : 0
                                                    Parameters.Now,
                                                    "FB"
                                                 );

                    /* reset user password */
                    dbAccount.ResetPassword(email);

                    account = dbAccount.Get(email);

                    #endregion
                }

                #region Login & Session operation

                LoginModel model = new LoginModel();
                model.UserName = account.Email;

                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                ActiveAccount activeAccount = new ActiveAccount();

                activeAccount.AccountId = account.AccountId;
                activeAccount.UserName = account.Email;
                activeAccount.FirstName = account.FirstName;
                activeAccount.LastName = account.LastName;
                activeAccount.Email = account.Email;
                activeAccount.Mobile = account.Mobile;
                activeAccount.BasketLocked = account.BasketLocked;
                activeAccount.IsManager = account.IsManager;
                activeAccount.IsSeoManager = account.IsSeoManager;
                activeAccount.IsReportManager = account.IsReportManager;
                activeAccount.IsAllowedBuyPrice = account.IsAllowedBuyPrice;
                activeAccount.AccountType = 0;
                activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                #region Cart Summary

                CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                activeAccount.TotalQty = summary.TotalQty;
                activeAccount.TotalPrice = summary.TotalPrice;
                activeAccount.InstallmentPrice = summary.InstallmentPrice;
                activeAccount.InstallmentTax = summary.InstallmentTax;

                #endregion

                #region Related Lists

                //activeAccount.RelatedLists = dbWishLists.GetUserRelatedLists(activeAccount.AccountId);

                #endregion

                ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();

                int productToAddCart = eStoreUser.ProductIdToAddCart;
                string productVariantToAddCart = eStoreUser.ProductVariantToAddCart;
                bool installmentSelected = eStoreUser.InstallmentSelected;
                int productAmountToAddCart = eStoreUser.ProductAmountToAddCart;

                Session["eStoreUser"] = activeAccount;

                if (!string.IsNullOrEmpty(activeAccount.RedirectUrl))
                {
                    return Redirect(activeAccount.RedirectUrl);
                }
                else if (productToAddCart > 0)
                {
                    if (Parameters.AllowVisitorsToUsingCart)
                    {
                        dbCart.VisitorToUser(VisitorId, activeAccount.AccountId);
                        return RedirectToAction("Index", "Cart");
                    }
                    else
                    {
                        dbCart.Insert(activeAccount.AccountId, 0, 0, productToAddCart, productAmountToAddCart, 0, false, installmentSelected, Parameters.Now, productVariantToAddCart, activeAccount.AccountType);
                        return RedirectToAction("Index", "Cart");
                    }
                }

                #endregion

            }
            catch (Exception e)
            {
                Logger.Write(e, "Exception");
            }
            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region TwitterLogin

        [HttpGet]
        public ActionResult TwitterLogin(string id, string name)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(name))
            {
                //WebClient client = new WebClient();
                #region Get user details

                //string jsonUserInfoResult = client.DownloadString(string.Concat("https://graph.facebook.com/me?access_token=", string.Empty));
                //JObject jsonUserInfo = JObject.Parse(jsonUserInfoResult);

                string email = string.Format("{0}@twitter.com", id); //jsonUserInfo.Value<string>("email");
                //string name = jsonUserInfo.Value<string>("name");
                string firstName = name; //jsonUserInfo.Value<string>("first_name");
                string lastName = string.Empty; //jsonUserInfo.Value<string>("last_name");

                #endregion

                Account account = dbAccount.Get(email);
                if (account == null)
                {
                    #region New account operation
                    int newId = (int)dbAccount.Insert(
                                                    firstName,
                                                    lastName,
                                                    email,
                                                    new DateTime(1900, 1, 1),
                                                    string.Empty, //Address1,
                                                    string.Empty, //Address2,
                                                    string.Empty, //Address3,
                                                    string.Empty, //Address4,
                                                    0,            //City,
                                                    string.Empty, //Phone,
                                                    string.Empty, //Mobile,
                                                    string.Empty, //Fax,
                                                    string.Empty, //PhoneInternational,
                                                    string.Empty, //Password,
                                                    1,            //NewsLetter == true ? 1 : 0
                                                    1,            //Campaign == true ? 1 : 0
                                                    Parameters.Now,
                                                    "TW"
                                                 );

                    /* reset user password */
                    dbAccount.ResetPassword(email);

                    account = dbAccount.Get(email);

                    #endregion
                }

                #region Login & Session operation

                LoginModel model = new LoginModel();
                model.UserName = account.Email;

                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                ActiveAccount activeAccount = new ActiveAccount();

                activeAccount.AccountId = account.AccountId;
                activeAccount.UserName = account.Email;
                activeAccount.FirstName = account.FirstName;
                activeAccount.LastName = account.LastName;
                activeAccount.Email = account.Email;
                activeAccount.Mobile = account.Mobile;
                activeAccount.BasketLocked = account.BasketLocked;
                activeAccount.IsManager = account.IsManager;
                activeAccount.IsSeoManager = account.IsSeoManager;
                activeAccount.IsReportManager = account.IsReportManager;
                activeAccount.IsAllowedBuyPrice = account.IsAllowedBuyPrice;
                activeAccount.AccountType = 0;
                activeAccount.RedirectUrl = eStoreUser.RedirectUrl;

                #region Cart Summary

                CartSummary summary = dbCart.GetSummary(activeAccount.AccountId, activeAccount.AccountType);
                activeAccount.TotalQty = summary.TotalQty;
                activeAccount.TotalPrice = summary.TotalPrice;
                activeAccount.InstallmentPrice = summary.InstallmentPrice;

                #endregion

                #region Related Lists

                //activeAccount.RelatedLists = dbWishLists.GetUserRelatedLists(activeAccount.AccountId);

                #endregion

                ViewData["StoreUserName"] = (activeAccount.FirstName + ' ' + activeAccount.LastName).TrimEnd();
                Session["eStoreUser"] = activeAccount;
                #endregion
            }
            return RedirectToAction("Index", "Home");
        }

        #endregion

        #region Index

        public ActionResult Index()
        {
            return View();
        }

        #endregion

        #region MsnLogin

        public ActionResult MsnLogin(string code)
        {
            string a = code;
            return View();
        }

        #endregion
    }
}
